<?php
namespace app\beautiful\controller\admin\project;
use app\BaseController;
use app\common\logic\DataLogic;
use app\beautiful\logic\order\OrderLogic;
use app\beautiful\logic\PartnerLogic;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\project\OnceCardItemModel;
use app\beautiful\model\project\OnceCardModel;
use app\beautiful\model\project\ProjectModel;
use app\beautiful\model\project\ProjectTypeModel;
use think\facade\Db;

class Oncecard extends BaseController{
    protected $name='次卡';

    public function index()
    {
        $name=$this->request->param('name');
        $status=$this->request->param('status/d',1);
        $is_flash_sale=$this->request->param('is_flash_sale/d',0);
        if(!in_array($status,[1,-1])) $status=1;

        $where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
            ['status','=',$status]
        ];
        if(!empty($name)) $where[]=['name','=',$name];


        $today=date("Y-m-d",$this->request->time());

        $once_card_model = new OnceCardModel();
        $once_card_model = $once_card_model->withCount(['items'=>function($query){
            $query->where([
                ['shop_id','=',$this->request->shopId],
                ['is_delete','=',0]
            ]);
        }]);
        if($is_flash_sale==1){
            $where[]=['is_flash_sale','=',1];
            $where[]=['start_time','<=',$today];
            $where[]=['end_time','>=',$today];
            $where[]=['flash_num','>',0];
        }else{
            $once_card_model=$once_card_model->whereRaw("(start_time > '{$today}' or end_time < '{$today}' or flash_num <= 0) OR is_flash_sale = 0");
        }
        $order=['sort'=>'desc','add_time'=>'desc'];
        $field='*';
        $append=['add_time_format','is_flash_sale_expire'];
        $return = DataLogic::getDataList($once_card_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        return $this->success($return);
    }

    public function show()
    {
        $once_card_id=$this->request->param('once_card_id/d',0);
        if($once_card_id==0) return $this->success([]);

        if(null === $once_card = OnceCardModel::find($once_card_id)) return $this->error($this->name.'不存在');
        if($once_card->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($once_card->is_delete != 0) return $this->error($this->name.'不存在');


        $once_card_items= OnceCardItemModel::with(['project'])->where([
            ['shop_id','=',$this->request->shopId],
            ['once_card_id','=',$once_card_id],
            ['is_delete','=',0]
        ])->select()->toArray();

        $project_items=[];$project_items_data=[];
        if(!empty($once_card_items)){
            foreach ($once_card_items as $k=>$v){
                $project_items[]=[
                    'project_id'=>$v['project_id'],
                    'num'=>$v['num'],
                ];

                $project_items_data[]=[
                    'project_id'=>$v['project_id'],
                    'cover_img'=>$v['project']['cover_img'],
                    'abbreviation'=>$v['project']['abbreviation'],
                    'market_price'=>$v['project']['market_price'],
                ];
            }
        }

        $detail=[
            'name'=>$once_card->name,
            'price'=>$once_card->price,
            'worth'=>$once_card->worth,
            'is_flash_sale'=>$once_card->is_flash_sale,
            'flash_price'=>$once_card->flash_price,
            'flash_num'=>$once_card->flash_num,
            'flash_sale_time'=>$once_card->flash_sale_time,
            'valid_time'=>$once_card->valid_time,
            'valid_unit'=>$once_card->valid_unit,
            'fictitious_take_count'=>$once_card->fictitious_take_count,
            'cover_img'=>$once_card->cover_img,
            'rotation'=>$once_card->rotation,
            'project_items'=>$project_items,
            'use_info'=>$once_card->use_info,
            'sort'=>$once_card->sort,
        ];

        return $this->success([ 'project_items'=>$project_items_data,'detail'=>$detail]);

    }

    public function save()
    {
        $once_card_id=$this->request->param('once_card_id/d',0);
        $name=$this->request->param('name');
        $price=$this->request->param('price/f',0);
        $worth=$this->request->param('worth/f',0);
        $is_flash_sale=$this->request->param('is_flash_sale/d',0);
        $flash_price=$this->request->param('flash_price/f',0);
        $flash_num=$this->request->param('flash_num/d',0);
        $flash_sale_time=$this->request->param('flash_sale_time/a',[]);
        $valid_time=$this->request->param('valid_time/d',0);
        $valid_unit=$this->request->param('valid_unit');
        $fictitious_take_count=$this->request->param('fictitious_take_count/d',0);
        $cover_img=$this->request->param('cover_img');
        $rotation=$this->request->param('rotation/a',[]);
        $project_items=$this->request->param('project_items/a',[]);
        $use_info=$this->request->param('use_info');
        $sort=$this->request->param('sort/d',0);

        //判断传来的参数
        if(empty($name)) return $this->error('请输入名称');
        if(empty($price) || $price <=0) return $this->error('请填写售价，且不能小于0');
        if(empty($worth) || $worth <=0) return $this->error('请填写总价值，且不能小于0');
        if($worth <= $price) return $this->error('总价值不能小于售价');
        if(!in_array($is_flash_sale,[0,1])) return $this->error('参数错误');
        if($is_flash_sale==1){
            if(empty($flash_price) || $flash_price<=0) return $this->error('请输入秒杀价,且不能小于0');
            if($flash_price>$price) return $this->error('秒杀价不能大于售价');
            if(empty($flash_num) || $flash_num<=0) return $this->error('秒杀数量不能小于0');
            if(empty($flash_sale_time) ||count($flash_sale_time) != 2) return $this->error('请选择秒杀时间');
            $start_time=$flash_sale_time[0]; $end_time=$flash_sale_time[1];
            if(false === $start_time_unix = strtotime($start_time)) return $this->error('请选择正确的秒杀开始时间');
            if(false === $end_time_unix = strtotime($end_time)) return $this->error('请选择正确的秒杀结束时间');
            if($end_time_unix<$start_time_unix) return $this->error('秒杀开始时间不能大于结束时间');
        }
        if(empty($valid_time) || $valid_time<=0) return $this->error('请输入有效期的值,且不能小于0');
        if(empty($valid_unit) || !in_array($valid_unit,['day','month','year'])) return $this->error('请选择有效期单位');
        if(empty($fictitious_take_count) || $fictitious_take_count <=0) return $this->error('请输入需要展示的销量');
        if(empty($cover_img)) return $this->error('请上传封面');
        if(empty($rotation) || !is_array($rotation) || count($rotation)>5) return $this->error('请上传轮播图，且数量不能多余5个');
        if(empty($use_info)) return $this->error('请填写使用说明');

        if(empty($project_items) || !is_array($project_items)) return $this->error('请选择项目');
        if(count($project_items)<=0) return $this->error('请选择项目');
        foreach ($project_items as $k => $v){
            if(!isset($v['project_id'])) return $this->error('参数错误');
            if(!isset($v['num'])) return $this->error('参数错误');
        }
        if($sort<0) return $this->error('请输入排序，且不能小于0');

        if($once_card_id != 0){
            if(null === $once_card = OnceCardModel::find($once_card_id)) return $this->error($this->name.'不存在');
            if($once_card->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
            if($once_card->is_delete != 0) return $this->error($this->name.'不存在');

//            $old_project_items=OnceCardItemModel::where([
//                ['shop_id','=',$this->request->shopId],
//                ['once_card_id','=',$once_card->once_card_id],
//                ['is_delete','=',0]
//            ])->select()->toArray() ?? [];
           $pre_rotation=$once_card->rotation;$pre_cover_img=$once_card->cover_img;
        }else{
            $once_card = new OnceCardModel();
            $once_card->shop_id  = $this->request->shopId;
            $old_project_items=[];$pre_rotation=[];$pre_cover_img=null;
        }

        $once_card->name=$name;
        $once_card->price=$price;
        $once_card->worth=$worth;
        $once_card->is_flash_sale=$is_flash_sale;
        if($is_flash_sale==1){
            $once_card->flash_price=$flash_price;
            $once_card->flash_num=$flash_num;
            $once_card->start_time=$start_time;
            $once_card->end_time=$end_time;
        }
        $once_card->valid_time=$valid_time;
        $once_card->valid_unit=$valid_unit;
        $once_card->fictitious_take_count=$fictitious_take_count;
        $once_card->cover_img=$cover_img;
        $once_card->rotation=$rotation;
        $once_card->sort=$sort;
        $once_card->use_info=$use_info;
        $once_card->status=1;
        $once_card->save();

//        foreach ($old_project_items as $k=>$v){
//            $old_project_items[$k]['is_delete']=1;
//        }

        OnceCardItemModel::where([
            ['shop_id','=',$this->request->shopId],
            ['once_card_id','=',$once_card->once_card_id],
        ])->save(['is_delete'=>1]);

        $project_ids=[];
        foreach ($project_items as $k => $v){
            if(!in_array($v['project_id'],$project_ids)){
                $project_items[$k]['shop_id']=$this->request->shopId;
                $project_items[$k]['once_card_id']=$once_card->once_card_id;
                $project_ids[]=$v['project_id'];
            }else{
                unset($project_items[$k]);
            }

        }

//        $new_project_items =array_merge($old_project_items,$project_items);
        $once_card_item_model=new OnceCardItemModel();
        $once_card_item_model->saveAll($project_items);

        //图片操作
        imgReplaceAct($cover_img,$pre_cover_img);
        arrayNoUseImg($pre_rotation); arrayUseImg($rotation);
        return $this->success('保存成功');

    }

    public function getProjectByIdsFromOncecard()
    {
        $project_ids=$this->request->param('project_ids/a',[]);
        if(empty($project_ids) || !is_array($project_ids)) return $this->error('参数错误');
        $where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
            ['project_id','in',$project_ids]
        ];

        $project_model= new ProjectModel();
        $order=['add_time'=>'desc'];
        $field='*';
        $append=['add_time_format'];
        $return = DataLogic::getDataList($project_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);
        return $this->success($return);
    }

    public function getProjectFromOncecard()
    {
        $name=$this->request->param('name');
        $where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
        ];

        if(!empty($name)) $where[]=['abbreviation','=',$name];
        $project_model= new ProjectModel();
        $order=['add_time'=>'desc'];
        $field='*';
        $append=['add_time_format'];
        $return = DataLogic::getDataList($project_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);
        return $this->success($return);
    }

    public function undercarriage()
    {
        $once_card_id=$this->request->param('once_card_id/d',0);
        if(null === $once_card = OnceCardModel::find($once_card_id)) return $this->error($this->name.'不存在');
        if($once_card->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($once_card->is_delete != 0) return $this->error($this->name.'不存在');
        if($once_card->status != 1) return $this->error($this->name.'已下架，请勿重复操作');

        $once_card->status=-1;
        $once_card->save();
        return $this->success('下架成功');
    }

    public function grounding()
    {
        $once_card_id=$this->request->param('once_card_id/d',0);
        if(null === $once_card = OnceCardModel::find($once_card_id)) return $this->error($this->name.'不存在');
        if($once_card->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($once_card->is_delete != 0) return $this->error($this->name.'不存在');
        if($once_card->status != -1) return $this->error($this->name.'已上架，请勿重复操作');

        $once_card->status=1;
        $once_card->save();
        return $this->success('上架成功');
    }

    public function del()
    {
        $once_card_id=$this->request->param('once_card_id/d',0);
        if(null === $once_card = OnceCardModel::find($once_card_id)) return $this->error($this->name.'不存在');
        if($once_card->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($once_card->is_delete != 0) return $this->error($this->name.'不存在');
        if($once_card->status != -1) return $this->error($this->name.'还未下架，请先下架在删除');

        $once_card->is_delete=1;
        $once_card->save();
        return $this->success('删除成功');
    }

    public function chooseOnceCard()
    {
        $name=$this->request->param('name');
        $member_id=$this->request->param('member_id/d',0);
        $where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
            ['status','=',1]
        ];
        if(!empty($name)) $where[]=['name','=',$name];


        $once_card_model = new OnceCardModel();
        $order=['sort'=>'desc','add_time'=>'desc'];
        $field='*';
        $append=['add_time_format','is_flash_sale_expire','flash_sale_djs','valid_time_format'];
        $return = DataLogic::getDataList($once_card_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);
        if($this->request->page==1){
            $member=MemberModel::find($member_id);
            $return['member']=[
                'level_id'=>$member===null ? 0 : $member->level_id,
                'member_id'=>$member===null ? 0 : $member->member_id,
            ];
        }
        return $this->success($return);
    }

    public function applyOnceCard()
    {
        $member_id=$this->request->param('member_id/d',0);
        $once_card_id=$this->request->param('once_card_id/d',0);
        $total_price=$this->request->param('total_price/f',0);
        $need_pay=$this->request->param('price/f',0);


        //判断传来的参数
        if($member_id ==0) return $this->error('会员不存在');
        if($once_card_id == 0) return $this->error('次卡不存在');
        if(empty($total_price) || $total_price <= 0) return $this->error('参数错误');
        if(empty($need_pay) || $need_pay <= 0) return $this->error('请输入实际价格，且不能小于0');

        $params=[
            'member_id'=>$member_id,
            'total_price'=>$total_price,
            'once_card_id'=>$once_card_id,
            'need_pay'=>$need_pay,
            'operate_type'=>2,
            'operate_id'=>$this->request->accountId,
        ];

        Db::startTrans();
        try{
            $order_logic = OrderLogic::init($this->request->shopId);
            $order_logic['once_card']->apply($params);

            //记录推广员业绩
            $PartnerLogic = new PartnerLogic($this->request->shopId);
            $PartnerLogic->commission($member_id,$need_pay);
            Db::commit();
            return $this->success('办理成功');
         }catch (\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
}
